﻿using System.Text.Json;
using TodayApp.Models;

namespace TodayApp.Services;

public class TodayPoetryService : ITodayPoetryService {
    private readonly IAlertService _alertService;

    public TodayPoetryService(IAlertService alertService) {
        _alertService = alertService ??
            throw new ArgumentNullException(nameof(alertService));
    }

    public async Task<TodayPoetry> GetTodayPoetryAsync() {
        var httpClient = new HttpClient();

        HttpResponseMessage response;
        try {
            response =
                await httpClient.GetAsync("https://v2.jinrishici.com/token");
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            _alertService.Alert(e.Message);
            return new TodayPoetry {Snippet = "无寻处，唯有少年心"};
        }

        var json = await response.Content.ReadAsStringAsync();
        var tokenObject = JsonSerializer.Deserialize<Token>(json);
        var token = tokenObject.data;

        httpClient.DefaultRequestHeaders.Add("X-User-Token", token);
        try {
            response =
                await httpClient.GetAsync("https://v2.jinrishici.com/sentence");
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            _alertService.Alert(e.Message);
            return new TodayPoetry { Snippet = "无寻处，唯有少年心" };
        }

        json = await response.Content.ReadAsStringAsync();
        var sentenceObject = JsonSerializer.Deserialize<Sentence>(json);
        return new TodayPoetry {Snippet = sentenceObject.data.content};
    }
}

public class Token {
    public string data { get; set; }
}

public class Sentence {
    public Data data { get; set; }
}

public class Data {
    public string content { get; set; }
}